var order;
var customerSelected;
var globalTotal = 0;

function init() {
    order = new Order();
    customerSelected = undefined;
}

function clearInputs() {
    $('crediterMoney').writeAttribute({value: ''});
    $('crediterPassword').writeAttribute({value: ''});
}

function showCustomersList(transport) {
    var customersTable = $('customersTable');
    var customersList = new XML(transport.responseText);

    if(customersList.customer.length() > 0) {
	customersTable.update('');

	var columns = new Element('tr');
	columns.appendChild(new Element('th').update('Pr&eacute;nom'));
	columns.appendChild(new Element('th').update('Surnom'));
	columns.appendChild(new Element('th').update('Nom'));
	columns.appendChild(new Element('th').update('Cat.'));
	columns.appendChild(new Element('th').update('Solde'));
	customersTable.appendChild(columns);

	for each (var customer in customersList.customer) {
	    var trCustomer = new Element('tr', {
		onclick: 'setClient('+ customer.id +')'
	    });
	    trCustomer.addClassName('clickable');
	    trCustomer.appendChild(new Element('td').update(customer.firstname.toString()));

	    if(customer.nickname.toString() == customer.lastname.toString()) {
		trCustomer.appendChild(new Element('td').update('&nbsp;'));
	    }
	    else {
		trCustomer.appendChild(new Element('td').update(customer.nickname.toString()));
	    }

	    trCustomer.appendChild(new Element('td').update(customer.lastname.toString()));
	    trCustomer.appendChild(new Element('td').update(customer.category.toString()));
	    trCustomer.appendChild(new Element('td').update(new Number(customer.balance.toString()).toFixed(2) + ' &euro;').setStyle('text-align: right;'));
	    customersTable.appendChild(trCustomer);
	}
    }
    else {
	var trNoCustomer = new Element('tr');
	trNoCustomer.appendChild(new Element('td').update("Aucun r&eacute;sultat."));
	customersTable.update(trNoCustomer);
    }
}

function failed() {
    alert('something has failed !');
}

function customersRequest() {
    var customerNameValue = $F('customerName');
    var h = new Hash();
    h.set('customerName', customerNameValue);

    if(customerNameValue != "") {
	new Ajax.Request('GetCustomers', {
	    parameters: h,
	    onSuccess: function(transport) {
		showCustomersList(transport);
	    },
	    onFailure: function() {
		failed();
	    }
	});
    }
    else {
	$('customersTable').update('');
    }
}

function getProductInfo(productId) {
    var h = $H();
    h.set('productId', productId);

    new Ajax.Request('GetProduct', {
	parameters: h,
	onSuccess: function(transport) {
	    var productXML = new XML(transport.responseText);
	    order.newProduct(productId, productXML);
	},
	onFailure: function() {
	    failed();
	}
    });
}

var Customer = Class.create({
    initialize: function(id, gerant, balance) {
	this.id = id;
	this.gerant = gerant;
	this.balance = balance;
    },

    canAfford: function(bill) {
	if(this.gerant) {
	    return (this.balance - bill) >= -20;
	}
	else {
	    return bill <= this.balance;
	}
    }
});

function setClient(customerId) {
    var h = $H();
    h.set('customerId', customerId);

    new Ajax.Request('GetCustomer', {
	parameters: h,
	onSuccess: function(transport) {
	    var customerXML = new XML(transport.responseText);
	    var isGerant = (customerXML.gerant.toString() == 'true') ? true : false;
	    customerSelected = new Customer(customerId, isGerant, customerXML.balance);

	    var customerInfos = customerXML.firstname;

	    if(customerXML.nickname.toString() != customerXML.lastname.toString()) {
		customerInfos += ' "' + customerXML.nickname + '" ';
	    }

	    customerInfos += ' ' + customerXML.lastname;
	    customerInfos += ' - ' + customerXML.category;
	    customerInfos += '<br />' + new Number(customerXML.balance.toString()).toFixed(2) + ' &euro;';

	    customerInfos += ' [ <a href="javascript:showCrediterForm(true,false)" id="crediterLink">Cr&eacute;diter</a> ]';

	    $('customerInfo').update(customerInfos);
	    showCrediterForm(false, false);
	    order.updateView();
	},
	onFailure: function() {
	    failed();
	}
    });
}

function credit(andPay) {
    var somme = $F('crediterMoney');
    var password = $F('crediterPassword');

    if(somme.blank() || password.blank()) {
	alert('Erreur ! Veuillez remplir tous les champs.');
    }
    else {
	if(isNaN(somme)) {
	    alert('Erreur ! La somme doit être un nombre.');
	}
	else {
	    var diff = new Number(globalTotal - new Number(customerSelected.balance.toString())).toFixed(2);

	    if(andPay && new Number(somme.toString()) < diff) {
		alert('Erreur ! Somme insuffisante. Minimum requis pour commander : ' + diff.toString());
	    }
	    else {
		var h = $H();
		h.set('customerId', customerSelected.id);
		h.set('somme', somme);
		h.set('password', password);

		new Ajax.Request('CrediterCustomer', {
		    parameters: h,
		    onSuccess: function(transport) {
			var status = transport.responseText;

			if(status == "true") {
			    setClient(customerSelected.id);
			    customersRequest();

			    if(andPay) {
				pay(true);
			    }
			    else {
				alert('Client crédité !');
			    }
			}
			else {
			    alert('Erreur ! Mauvais mot de passe.');
			    $('crediterPassword').writeAttribute({
				value: 'a'
			    });
			}
		    },
		    onFailure: function() {
			failed();
		    }
		});
	    }
	}
    }
}

function pay(creditBefore) {
    var productsList = '';
    var quantity = '';

    order.products.each(function(pair) {
	var product = pair.value;
	productsList += product.productId.toString() + ' ';
	quantity += product.quantity.toString() + ' ';
    });

    var h = $H();
    h.set('customerId', customerSelected.id);
    h.set('productsList', productsList.strip());
    h.set('quantity', quantity.strip());

    new Ajax.Request('PayProducts', {
	parameters: h,
	onSuccess: function(transport) {
	    setClient(customerSelected.id);
	    if(creditBefore) {
		alert('Client crédité et débité.');
	    }
	    order.cancel();
	    customersRequest();
	},
	onFailure: function() {
	    failed();
	}
    });
}

function showCrediterForm(showForm, bill) {
    var subtitle = $('cmdTransaction');
    var form = $('crediterForm');
    var link = $('crediterLink');
    var button = $('crediterButton');

    if(showForm) {
	form.show();
	subtitle.show();
	link.writeAttribute({
	    href: 'javascript:showCrediterForm(false,false)'
	});
	link.update('Annuler');

	if(bill) {
	    subtitle.update('Cr&eacute;diter & Commander');
	    button.writeAttribute({
		value: 'Créditer & Commander',
		onclick: 'credit(true)'
	    });
	}
	else {
	    subtitle.update('Cr&eacute;diter');
	    button.writeAttribute({
		value: 'Créditer',
		onclick: 'credit(false)'
	    });
	}
    }
    else {
	form.hide();
	subtitle.hide();
	link.writeAttribute({
	    href: 'javascript:showCrediterForm(true, false)'
	});
	link.update('Cr&eacute;diter');
    }
}

var Product = Class.create({
    initialize: function(productId, description, price) {
	this.productId = productId;
	this.description = description;
	this.price = price;
	this.quantity = 1;
    },

    plus: function() {
	this.quantity += 1;
    },

    minus: function() {
	if(this.quantity > 1) {
	    this.quantity -= 1;
	}
    }
});

var Order = Class.create({
    initialize: function() {
	this.products = $H();
    },

    addProduct: function(productId) {
	if(this.products.get(productId) != undefined) {
	    this.products.get(productId).plus();
	    this.updateView();
	}
	else {
	    getProductInfo(productId);
	}
    },

    newProduct: function(productId, productXML) {
	this.products.set(productId, new Product(productId, productXML.name, productXML.price));
	this.updateView();
    },

    removeProduct: function(productId) {
	var product = this.products.get(productId);

	if(product != undefined) {
	    if(product.quantity > 1) {
		product.minus();
	    }
	    else {
		this.products.unset(productId);
	    }
	}

	this.updateView();
    },

    cancel: function() {
	this.products = $H();
	this.updateView();
	globalTotal = new Number(0);
    },

    updateView: function() {
	var productsList = $('productsList');
	productsList.update('');

	if(this.products.size() > 0) {
	    var total = 0;
	    var trColumns = new Element('tr');
	    trColumns.appendChild(new Element('th').update('Qte.'));
	    trColumns.appendChild(new Element('th').update('Description'));
	    trColumns.appendChild(new Element('th').update('Total'));
	    productsList.appendChild(trColumns);

	    this.products.each(function(pair) {
		var product = pair.value;
		var subPrice = product.quantity * product.price;
		total += subPrice;
		var trProduct = new Element('tr', {
		    onclick: 'order.removeProduct('+ product.productId +')'
		});
		trProduct.addClassName('clickable');
		trProduct.appendChild(new Element('td').update(product.quantity.toString() + 'x').setStyle('text-align: right;'));
		trProduct.appendChild(new Element('td').update(product.description.toString() + ' (' + new Number(product.price).toFixed(2) + ' &euro;)'));
		trProduct.appendChild(new Element('td').update(new Number(subPrice).toFixed(2) + ' &euro;'));
		productsList.appendChild(trProduct);
	    });

	    var trTotal = new Element('tr');
	    trTotal.appendChild(new Element('th', {
		colspan: '2'
	    }).update('Total'));
	    trTotal.appendChild(new Element('th').update(new Number(total).toFixed(2) + ' &euro;'));
	    globalTotal = new Number(total);
	    productsList.appendChild(trTotal);

	    var trButtons = new Element('tr');
	    var tdButtons = new Element('td', {
		colspan: '4',
		style: 'text-align: center;'
	    });

	    tdButtons.appendChild(new Element('input', {
		type: 'submit',
		onclick: 'order.cancel()',
		value: 'Annuler'
	    }));

	    var envoyerButton = new Element('input', {
		type: 'submit',
		value: 'Commander'
	    });

	    if(customerSelected == undefined) {
		envoyerButton.writeAttribute({
		    disabled: 'disabled'
		});
	    }
	    else {
		if(customerSelected.canAfford(total)) {
		    envoyerButton.writeAttribute({
			onclick: 'pay()'
		    });
		}
		else {
		    envoyerButton.writeAttribute({
			value: 'Créditer & Commander',
			onclick: 'showCrediterForm(true, true)'
		    });
		}
	    }

	    tdButtons.appendChild(envoyerButton);

	    trButtons.appendChild(tdButtons);
	    productsList.appendChild(trButtons);
	}
	else {
	    productsList.update('<tr><td style="text-align: center;">S&eacute;lectionner un ou plusieurs produit en utilisant la zone <i>Produits</i>.</td></tr>');
	}
    }
});

function adminCustomersRequest() {
    var customerNameValue = $F('customerName');
    var h = new Hash();
    h.set('customerName', customerNameValue);

    if(customerNameValue != "") {
	new Ajax.Request('../GetCustomers', {
	    parameters: h,
	    onSuccess: function(transport) {
		adminShowCustomersList(transport);
	    },
	    onFailure: function() {
		failed();
	    }
	});
    }
    else {
	$('customersTable').update('');
    }
}

function adminShowCustomersList(transport) {
    var customersTable = $('customersTable');
    var customersList = new XML(transport.responseText);

    if(customersList.customer.length() > 0) {
	customersTable.update('');

	var columns = new Element('tr');
	columns.appendChild(new Element('th').update('Pr&eacute;nom'));
	columns.appendChild(new Element('th').update('Surnom'));
	columns.appendChild(new Element('th').update('Nom'));
	columns.appendChild(new Element('th').update('Cat.'));
	columns.appendChild(new Element('th').update('Solde'));
	columns.appendChild(new Element('th').update('Action'));
	customersTable.appendChild(columns);

	for each (var customer in customersList.customer) {
	    var trCustomer = new Element('tr');
	    //onclick: 'setClient('+ customer.id +')'
	    trCustomer.appendChild(new Element('td').update(customer.firstname.toString()));

	    if(customer.nickname.toString() == customer.lastname.toString()) {
		trCustomer.appendChild(new Element('td').update('&nbsp;'));
	    }
	    else {
		trCustomer.appendChild(new Element('td').update(customer.nickname.toString()));
	    }

	    trCustomer.appendChild(new Element('td').update(customer.lastname.toString()));
	    trCustomer.appendChild(new Element('td').update(customer.category.toString()));
	    trCustomer.appendChild(new Element('td').update(customer.balance.toString() + ' &euro;'));
	    var link = new Element('a',{
		href: 'customers/edit?id='+customer.id
	    });
	    link.update('Editer');
	    trCustomer.appendChild(new Element('td').appendChild(link));
	    trCustomer.appendChild(new Element('td'))
	    customersTable.appendChild(trCustomer);
	}
    }
    else {
	var trNoCustomer = new Element('tr');
	trNoCustomer.appendChild(new Element('td').update("Aucun r&eacute;sultat."));
	customersTable.update(trNoCustomer);
    }
}
